<?php

defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.controller');


class SEventController extends JController
{
	function display()
	{
		// Add com custom css file into header
		$doc =& JFactory::getDocument();
		$href = JURI::base().'/components/com_sevent/assets/stylesheets/style.css';
		$attribs = array('type' => 'text/css');
		$doc->addHeadLink( $href, 'stylesheet', 'rel', $attribs );
		
		parent::display();
	}
	
	function newEvent()
	{
		JRequest::checkToken('GET') or jexit( 'Invalid Token' );
		
		JRequest::setVar('view', 'events');
		JRequest::setVar('layout','newevent') ;
            	
    	$this->display();
	}
	
	function submitNewSevent()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		$model = $this->getModel('Events') ;
		
		$id = $model->storeEvent();
		
		//Check email notification
		SEventController::notifyUsersByEmail($id);
		
		$app = JFactory::getApplication();
		$link = JRoute::_('index.php?option=com_sevent&view=events') ;
		
		$app->redirect($link) ;
		
	}
	
	function changeComment()
	{
		JRequest::checkToken() or jexit( 'Invalid Token' );
		
		$comment = JRequest::getVar('se_new_comment');
		$id = JRequest::getVar('event_id');
		
		$model = $this->getModel('Events') ;
		
		$model->changeComment($id, $comment);
		
		$app = JFactory::getApplication();
		$link = JRoute::_('index.php?option=com_sevent&view=events') ;
		
		$app->redirect($link) ;
	}
	
	function newParticipant()
	{
		JRequest::checkToken('GET') or jexit( 'Invalid Token' );
		
		$model = $this->getModel('Events') ;
		$model->storeParticipant();
		
		$app = JFactory::getApplication();
		$link = JRoute::_('index.php?option=com_sevent&view=events') ;
		
		$app->redirect($link) ;
	}
	
	function notifyUsersByEmail($event_id)
	{
		$model = $this->getModel('Events') ;
		$event = $model->getEvent($event_id);
		
		if((JRequest::getBool('inputNotification')) == true)
		{
			//Fetch email object
			$mailer =& JFactory::getMailer();
			
			//Set the sender
			$config =& JFactory::getConfig();
			$sender = array(
					$config->getValue( 'config.mailfrom' ),
					$config->getValue( 'config.fromname' ) );
			$mailer->setSender($sender);
			
			//Set the recipient
			$mailer->addRecipient('mtbberoun@googlegroups.com');
			
			
			$user = JFactory::getUser($event->user_id);
			$username=$user->get('username');
			
			//Set the email
			$mailer->Encoding = 'base64';
			
			$body   = "Ahoj, \nuživatel " . $username ." Vás zve na následující událost: ". $event->event_type ."\n".
					"v následujícím termínu: ". $event->date_time ."\n".
					"Ostatní informace naleznete na našem webu http://www.morethanbikers.cz";
			$mailer->setSubject('Pozvánka na novou událost');
			$mailer->setBody($body);
			
			//Send the email
			$mailer->Send();
		}
	}
}